package top.jiangqiang.qyblog.core.init;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import top.jiangqiang.qyblog.common.config.GlobalProperties;
import top.jiangqiang.qyblog.common.exception.JsonException;
import top.jiangqiang.qyblog.core.service.IAdminUserService;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 项目启动后使用指定的dataSource自动执行sql脚本，如果有多个数据源可以通过注入多个数据源对应的IDdl实现
 *
 * @author Jiangqiang
 * @version 1.0
 * @date 2023/4/26 10:12
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class InitUser implements ApplicationRunner {
    @Value("${user.username:}")
    private String username;
    @Value("${user.password:}")
    private String password;

    private final GlobalProperties globalProperties;
    private final IAdminUserService adminUserService;

    @Override
    public void run(ApplicationArguments args) {
        try {
            Set<GlobalProperties.UserConfig> userConfigs = globalProperties.getUsers().stream()
                    .filter(userConfig -> {//过滤不合法的配置
                        String tmpUsername = userConfig.getUsername();
                        String tmpPassword = userConfig.getPassword();
                        return StrUtil.isNotBlank(tmpUsername) && StrUtil.isNotBlank(tmpPassword);
                    }).map(userConfig -> new GlobalProperties.UserConfig(userConfig.getUsername().trim(), userConfig.getPassword().trim()))
                    .collect(Collectors.toSet());
            if (StrUtil.isNotBlank(username) && StrUtil.isNotBlank(password)) {
                GlobalProperties.UserConfig userConfig = new GlobalProperties.UserConfig();
                userConfig.setUsername(username.trim());
                userConfig.setPassword(password.trim());
                userConfigs.add(userConfig);
            }
            if (userConfigs.size() == 0) {
                throw new JsonException("没有配置管理员账户信息");
            }
            int size = userConfigs.stream()
                    .map(GlobalProperties.UserConfig::getUsername)
                    .collect(Collectors.toSet()).size();
            if (size < userConfigs.size()) {
                throw new JsonException("用户名配置重复");
            }
            adminUserService.initUsers(userConfigs);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }
}
